﻿using UnityEngine;
using System.Collections;

/* Comment
 * 部队移动的帮助文件，包含2个部分
 * 1.选定移动的UI，一个贴近地面的框。全局公用，
 * 2.当前目标地点的指示器。全局公用
 * 帮助文件每个军团包含一个
 */

public class SelectSquareArgs : System.EventArgs
{
	public bool bSelect;

	public SelectSquareArgs(bool bSel)
	{
		bSelect = bSel;
	}
}

public class PickTargetArgs : System.EventArgs
{
	public Vector3 position;
	public GameObject hitObj;

	public PickTargetArgs(GameObject hit, Vector3 pos)
	{
		position = pos;
		hitObj = hit;
	}
}

public class MoveHelper : MonoBehaviour {
	
	public event System.EventHandler<SelectSquareArgs> selSquare;
	public event System.EventHandler<PickTargetArgs> pickTarget;

	public PlayerForces forces;

	public GameObject quadHelper;

	public UserInputManager inputmgr;

	Square sqr;
	SquareMove sqrMov;

	// Use this for initialization
	void Start () {
		if (null == quadHelper)
		{
			Debug.LogError(this.gameObject.name + " not have a HelpQuad child!!");
		}

		sqr = gameObject.GetComponent<Square> ();
		sqrMov = gameObject.GetComponent<SquareMove> ();
		inputmgr.evthMouseInput += UserInput;
	}
	
	// Update is called once per frame
	void Update () {
		UpdateHelperState (sqr);
	}

	void UpdateHelperState(Square sqr)
	{
		UpdateSqrHelper (sqr);
	}

	void UpdateSqrHelper(Square sqr)
	{
		//quadHelper.SetActive (true);
		
		if (sqr.IsSelect)
		{
			quadHelper.transform.position = sqrMov.DstPosition;
			quadHelper.transform.Translate (new Vector3 (0f, 0f, -1f));
			quadHelper.transform.rotation = sqrMov.DstOrientation;
			quadHelper.transform.Rotate (new Vector3 (90, 0, 0));
		}
	}

	void UserInput(object sender, EventMouseInput input)
	{
		if (input.eTarget != ESelTarget.emSelSquare || input.dstObj != this.gameObject)
				return;

		if (Input.GetMouseButton (0)){
			
			Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
			
			RaycastHit[] hits = Physics.RaycastAll(ray);
			
			if (!sqr.IsSelect)
			{
				foreach (RaycastHit hit in hits)
				{
					if(hit.collider.gameObject.tag == "Square")
					{
						selSquare(this.gameObject.GetComponent<Square>(), new SelectSquareArgs(true));
						break; 
					}
				}
			}
			else
			{
				foreach (RaycastHit hit in hits)
				{
					if(hit.collider.gameObject.tag == "Ground")
					{
						Vector3 quad = hit.point;
						quad.y = 0.1f;
						
						pickTarget(this.gameObject.GetComponent<Square>(), new PickTargetArgs(hit.collider.gameObject, hit.point));
						break;
					}
				}
			}
		}
		
		if (Input.GetMouseButtonUp (0)){
			if (sqr.IsSelect)
			{
				selSquare(this.gameObject.GetComponent<Square>(), new SelectSquareArgs(false));
			}
		}
	}
}
